package com.heng.futureDemo;

import org.junit.Test;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class ACompletableFutureAPIDemo10 {
    public static void main(String[] args) {

        ExecutorService threadPool = Executors.newFixedThreadPool(3);
        CompletableFuture.supplyAsync(() -> {
            try {TimeUnit.SECONDS.sleep(1);} catch (InterruptedException e) {e.printStackTrace();}
            System.out.println("111");
            return 1;
        },threadPool).thenApply(f -> {
            System.out.println("222");
            return f + 2;
        }).thenApply(f -> {
            System.out.println("333");
            return f + 3;
        }).whenComplete((v,e) -> {
            if(e == null) {
                System.out.println("---计算结果： " + v);
            }
        }).exceptionally(e ->{
            e.printStackTrace();
            System.out.println(e.getMessage());
            return null;
        });
//        try {TimeUnit.SECONDS.sleep(11);} catch (InterruptedException e) {e.printStackTrace();}
        System.out.println(Thread.currentThread().getName()+"---主线程忙其他任务");
        threadPool.shutdown();
    }

    @Test
    public void m1(){
        ExecutorService threadPool = Executors.newFixedThreadPool(3);
        CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread().getName()+"\t");
            return 1;
        },threadPool).thenApply(f -> {
            System.out.println(Thread.currentThread().getName()+"\t"+f);
            return f + 2;
        }).whenComplete((v,e)->{
            if(e==null) {
                v+=1;
                System.out.println(Thread.currentThread().getName()+"\t"+v);
            }
        }).exceptionally(e->{
            System.out.println(e.getMessage());
            return null;
        });


        // 阿里云，世界还是很大的，很多美丽的风景在等着你呀！
        System.out.println(completableFuture.join());
        threadPool.shutdown();

    }
}
